package com.gobang.modules.login;

import com.gobang.entity.User;
import com.gobang.proto.GameProto.*;
import com.gobang.modules.message.MessageService;
import com.gobang.modules.player.PlayerService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录业务服务
 */
@Slf4j
@Service
public class LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private PlayerService playerService;
    @Autowired
    private MessageService messageService;

    /**
     * 处理登录请求
     */
    public void handleLogin(ChannelHandlerContext ctx, LoginRequest request) {
        User user = userService.loginOrRegister(request.getUsername(), request.getPassword());

        if (user == null) {
            LoginResponse response = LoginResponse.newBuilder()
                    .setSuccess(false)
                    .setMessage("用户名或密码错误")
                    .build();
            messageService.sendMessage(ctx, MessageType.LOGIN_RESPONSE, response.toByteArray());
            return;
        }

        // 保存用户连接
        playerService.addPlayer(user.getId(), ctx);

        LoginResponse response = LoginResponse.newBuilder()
                .setSuccess(true)
                .setMessage("登录成功")
                .setUserId(user.getId())
                .setUsername(user.getUsername())
                .setScore(user.getScore())
                .setWinCount(user.getWinCount())
                .setLoseCount(user.getLoseCount())
                .build();

        messageService.sendMessage(ctx, MessageType.LOGIN_RESPONSE, response.toByteArray());
        log.info("用户登录成功: userId={}, username={}", user.getId(), user.getUsername());
    }
}
